package com.gxa.worker.recycling.service.impl;

import com.gxa.core.recycling.common.ExceptionCode;
import com.gxa.core.recycling.exception.BusinessException;
import com.gxa.core.recycling.pojo.*;
import com.gxa.worker.recycling.mapper.*;
import com.gxa.worker.recycling.repository.GoodsRepository;
import com.gxa.worker.recycling.repository.ImgsRepository;
import com.gxa.worker.recycling.service.GoodsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @author Bei
 * @date 2021/12/2 17:56
 */
@Service
@Transactional(rollbackFor = {Throwable.class})
public class GoodsOrderServiceImpl implements GoodsOrderService {

    @Autowired
    GoodsorderMapper goodsorderMapper;

    @Autowired
    GoodsRepository goodsRepository;

    @Autowired
    ServiceAddressMapper serviceAddressMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RecyclerMapper recyclerMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    ScoreMapper scoreMapper;

    @Autowired
    ImgsRepository imgsRepository;

    @Autowired
    RecycleorderMapper recycleorderMapper;

    @Override
    public List<Map> selectByDelivered(Long rid) {
        Long hid = recycleorderMapper.villAgeId(rid);
        String villAgeName = recycleorderMapper.findVillAgeName(hid);
        List<Map> maps = goodsorderMapper.selectByDelivered(rid);
        for (int i = 0; i < maps.size(); i++) {
            maps.get(i).put("village",villAgeName);
        }
        return maps;

    }

    @Override
    public Integer countDelivered(Long hid) {
        List<Map> maps = goodsorderMapper.selectByDelivered(hid);
        return maps.size();
    }

    @Override
    public Integer countNoDelivered(Long hid) {
        List<Map> maps = goodsorderMapper.selectByNoDelivered(hid);
        return maps.size();
    }

    @Override
    public Map<String, Object> getDeepOrderInfo(Long id) throws BusinessException {
        //订单详细信息
        Goodsorder goodsorder = goodsorderMapper.selectByPrimaryKey(id);
        if (goodsorder==null) {
            throw new BusinessException(ExceptionCode.ORDER_ERROR);
        }
        List<Imgs> allByGidEquals = imgsRepository.findAllByGidEquals(goodsorder.getGid());
        Map<String, Object> goodsOrderByUserId = goodsorderMapper.getGoodsOrderById(id);
        goodsOrderByUserId.put("imgs",allByGidEquals);
        return goodsOrderByUserId;
    }

    @Override
    public void addOrder(Long uid, Long gid,Long recycleId) throws BusinessException {
        //生成商品兑换订单
        Goodsorder goodsorder = new Goodsorder();
        //取出兑换的商品信息
        Goods goods = goodsRepository.findGoodsByIdEquals(gid);
        if (goods==null) {
            throw new BusinessException(ExceptionCode.WAIT);
        }
        if (goods.getCounts()<=0) {
            throw new BusinessException(ExceptionCode.GOODNUM_ERROR);
        }
        //取出配送员信息
        Recycler recycler = recyclerMapper.selectByPrimaryKey(recycleId);
        //拿到用户信息
        User user = userMapper.selectByPrimaryKey(uid);
        //非临创用户
        if (!user.getType().contains("临创")) {
            throw new BusinessException(ExceptionCode.USERTYPE_ERROR);
        }
        //积分不足
        if (user.getNowPoints()<goods.getNeedPoints()) {
            throw new BusinessException(ExceptionCode.POINT_ERROR);
        }
        //给订单设置信息

        //商品id
        goodsorder.setGid(gid);
        //兑换码
        goodsorder.setCode((int)(Math.random()*9000)+1000+"");
        //兑换时间
        goodsorder.setExchangetime(new Date());
        //服务地址

        //查询是否已经拥有了服务地址
        Example example = new Example(ServiceAddress.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uid",uid);
        List<ServiceAddress> serviceAddresses = serviceAddressMapper.selectByExample(example);
        //存在
        ServiceAddress nowAddress = null;
        if (serviceAddresses.size()>0) {
            nowAddress = serviceAddresses.get(0);
        }else {
            //不存在地址就新建服务地址
            nowAddress = new ServiceAddress();
            nowAddress.setUid(uid);
            nowAddress.setCommnuityId(user.getQuartersId());
            nowAddress.setDaddress(user.getLocation());
            serviceAddressMapper.insert(nowAddress);
        }
        //设置服务地址
        goodsorder.setLocationId(nowAddress.getId());
        //设置数目
        goodsorder.setNumber(1);
        //设置配送员姓名
        goodsorder.setRecyclerName(recycler.getName());
        //订单状态
        goodsorder.setState("已收货");
        //设置总积分
        goodsorder.setTotal(goods.getNeedPoints());
        //设置订单创建人
        goodsorder.setUid(uid);
        //留言不设置
        //订单存储
        goodsorderMapper.insertSelective(goodsorder);

        //用户积分扣除
        user.setNowPoints(user.getNowPoints()-goods.getNeedPoints());
        userMapper.updateByPrimaryKeySelective(user);
        //积分明细新增
        Score score = new Score();
        score.setNum(goods.getNeedPoints());
        score.setChangetime(new Date());
        score.setSerson("兑换"+goods.getName());
        //积分减少 出账
        score.setStatus(false);
        score.setUid(uid);
        scoreMapper.insert(score);
        //商品库存减少
        goods.setCounts(goods.getCounts()-1);
        goodsMapper.updateByPrimaryKeySelective(goods);
        //mongo更新库存,删除再添加
        goodsRepository.deleteByIdEquals(gid);
        goodsRepository.save(goods);


    }

    @Override
    public List<Map<String, Object>> getOrdersByRecyclerId(Long id) {
        List<Map<String, Object>> orderByRecyclerId = goodsorderMapper.getOrderByRecyclerId(id);
        return orderByRecyclerId;
    }

    @Override
    public void finishOrderById(Long id,Long recyclerId) {
        //取出带配送订单
        Goodsorder goodsorder = goodsorderMapper.selectByPrimaryKey(id);
        //取出配送员
        Recycler recycler = recyclerMapper.selectByPrimaryKey(recyclerId);
        //完善订单信息
        //库存减一操作在用户前台产生   积分明细表增加一条记录在用户前台产生   用户积分减少在兑换订单产生时完成
        goodsorder.setRecyclerName(recycler.getName());
        goodsorder.setState("已收货");
        goodsorder.setCode((int)(Math.random()*9000)+1000+"");
        goodsorderMapper.updateByPrimaryKeySelective(goodsorder);
    }
}
